<!--
**********************************************************
* @Author: 张小平
* @Date:   2024-05-01
* @Email:  qqshuqian@163.com
* @Last modified: 最后修改日期
* @Description: 文件描述
**********************************************************
-->
<template>

  <div class="select" >
    <el-tag closable
            :disable-transitions="true"
            v-for="tag in selectedData"
            :key="tag.index"
            @close="handleCloseUser(tag)"
    >
      {{ tag[filedLable] }}
    </el-tag>
    <el-button icon="el-icon-plus" circle class="new-tag" size="small" @click="toShow" />
    <el-button style="margin-left: 10px" v-if="selectedData && selectedData.length>0"   v-show="isDo" @click="handleClearTag">清空</el-button>

  </div>

  <el-dialog title="选择" v-model="isShow" class="userSelectDialog"  append-to-body>



    <el-container style="height: 600px;width: 100%">

      <el-main height="500px" class="userSelectDiv2">
      <avue-crud
          v-model:search="form"
          v-model:page="page"
          v-bind="bindVal"
          v-on="onEvent"
          :option="option"
          :data="tableData"
          @selection-change="selectionChange"
          :before-open="beforeOpen"
      >
        <template #menu="{size,row,index}">
          <el-button v-if="showSelectedBtn" link type="primary"  size="small" icon="el-icon-lock" @click="selectionClick(row)">选择</el-button>
        </template>

      </avue-crud>
    </el-main>

      <div class="selected-user" >
        <div>
          <span>已选择的用户：</span>
          <div>
            <el-tag class="el-tag-line"  v-for="d in selectedData">{{d[filedLable]}}</el-tag>
          </div>
        </div>

        <div>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button type="primary" @click="isShow=false">取消</el-button>
        </div>
      </div>


    </el-container>

  </el-dialog>


</template>
<script>

  import request from '@/framework-core/axios';
  import website from '@/framework-core/config/website';
  import { convertHtmlByParam,convertVantMobile,removeEmptyFields,loadEChartsScript} from '@/framework-core/utils/util'
  import _ from "lodash";

  export default {
    name: "dftable",
    props: ['column','modelValue'],
    inject: ['getViewFormData'],
      data() {
        return {
          selectedData: [],
          isShow: false,
          multiple: false,
          rangList: [],
          tableSearchVisible: false,
          tableData: [],
          selectedKey:"",
          formData:{},
          pageConfig: {
            "url": "/form/tableData",
            absoluteUrl: website.baseUrl + "/api/form/tableData/download2?type=1",
            name: "导入",
            params: {"": ""}
          },
          loading: false,
          form: {},
          sysParamForm: {},
          option: {},
          tableDicMap: {},
          queryFormData: {},
          sortData: {
            sort: "", order: ""
          },
          page: {
            total: 0, // 总页数
            currentPage: 1, // 当前页数
            pageSize: 20 // 每页显示多少条
          },
        };
      },
    watch: {
      modelValue: {
        handler () {
          if(this.modelValue && (!this.selectedData || this.selectedData.length==0)){
            this.selectedData = this.getDefSelected();
          }
        }
      }
    },
    computed: {
      filedLable: function (){
        return this.column.filedLable||"id";
      },
      isHideUserSelected: function () {
        if(!this.column){
          return true;
        }
        return !(this.column["hideUserSelected"] ||false);
      },
      isDo: function () {
        if(!this.column){
          return false;
        }
        return !this.column.disabled;
      },

      showSelectedBtn: function () {
        return window.isMobile;
      },
      bindVal() {
        return {
          ref: 'crud'
        }
      },
      onEvent() {
        return {
          'refresh-change': this.refreshChange,
          'search-reset': this.searchChange,
          'search-change': this.searchChange,
          'current-change': this.currentChange,
          'sort-change':this.sortChange
        }
      },
      onEventSort() {
        return {
          'sort-change':this.sortChange
        }
      },

    },
    mounted(){
      if( this.getViewFormData){
        this.formData = this.getViewFormData()
      }
    },
    created() {

    },

    methods: {
      toShow() {
        this.isShow = true;
        if (window.isMobile) {
          this.page.layout = "total,prev, next";
        }
        this.getFormJson();
        if (this.column) {
          this.multiple = this.column.multiple || this.column.multipleTest || false;
        }
      },
      getFormJson() {
        this.pageConfig.params = {};
        this.pageConfig.params.app = this.column.appCode;
        this.option = {
          "border": true,
          "index": true,
          "indexLabel": "#",
          "stripe": true,
          "menuAlign": "center",
          "align": "center",
          searchLabelWidth: 150,
          grid: window.isMobile,
          editBtn: false,
          delBtn: false,
          addBtn: false,
          reserveSelection: true,
          selection:true,
          gridSpan: 24,
          searchMenuSpan: 6,
          menu:  window.isMobile,
          searchEnter: true,
          "column": []
        };

        return request({
          url: website.baseUrl+'/api/form/queryApp/queryByApp',
          method: 'post',
          params: {"app": this.pageConfig.params.app}
        }).then(response => {

          this.queryFormData = response.data.data;

          // 系统参数
          if (this.queryFormData.param) {
            for (let indexa = 0; indexa < this.queryFormData.param.length; indexa++) {
              var paramTemp = this.queryFormData.param[indexa];
              this.sysParamForm[paramTemp.pkey] = paramTemp.pvalue;
            }
          }


          let mapCols = {};
          if (this.queryFormData.form) {
            let optionForm = eval("(" + this.queryFormData.form.modelJson + ")") || {};
            optionForm.column.forEach((column) => {
              mapCols[column.prop] = column;
            });

          }

          if (this.queryFormData.models) {
            let selectcolumns = [];

            for (let indexf = 0; indexf < this.queryFormData.models.length; indexf++) {
              let fied = this.queryFormData.models[indexf];

              if (!!fied.isQuery) {
                let selectcolumn = {
                  "type": fied.columnShowType || "input",
                  "label": fied.label,
                  "labelWidth": 120,
                  "prop": fied.prop,
                  'search': !!fied.queryType && fied.queryType != "range",
                  "span": 12
                }

                if ("id" == selectcolumn.prop) {
                  selectcolumn.hide = true;
                  selectcolumn.display = false;
                }
                if ("createrName" == selectcolumn.prop) {
                  selectcolumn.display = false;
                }
                switch (selectcolumn.type) {
                  case "input":
                    break;
                  case "number":

                    break;
                  case "select":
                    //selectcolumn.dicData = this.$dictObject[fied.dicValue];

                    if (this.queryFormData.dics && fied.dicValue) {
                      selectcolumn.dicData = this.queryFormData.dics[fied.dicValue];
                    }
                    break;
                  case "radio":
                    selectcolumn.dicData = this.queryFormData.dics[fied.dicValue];
                    break;
                  case "checkbox":
                    selectcolumn.dicData = this.queryFormData.dics[fied.dicValue];
                    break;
                  case "switch":
                    selectcolumn.dicData = [{"label": "否", "value": 0}, {"label": "是", "value": 1}];
                    break;
                  case "date":
                    selectcolumn.format = 'YYYY年MM月DD日';
                    break;
                  case "datetime":
                    selectcolumn.format = 'YYYY年MM月DD日 hh:mm';
                    break;
                  case "year":
                    selectcolumn.format = 'YYYY年';
                    break;
                  case "week":
                    selectcolumn.dateformat = "week";
                    //selectcolumn.type=  "input",
                    break;
                  case "month":
                    selectcolumn.format = 'YYYY年MM月';
                    break;
                  case "time":
                    selectcolumn.format = 'hh:mm';
                    break;
                  case "cascader":
                    break;
                  case "upload":
                    selectcolumn.type = "upload";
                    selectcolumn.listType = "picture-img";
                    selectcolumn.addDisplay = false;
                    selectcolumn.editDisplay = false;
                    selectcolumn.propsHttp = {"url": 'url', "name": 'name', res: 'data.data'};
                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";
                    break;
                  case "ueditor":
                    selectcolumn.type = "ueditor";
                    selectcolumn.overHidden = true;
                    selectcolumn.component = "avueUeditor";
                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";

                    selectcolumn.propsHttp = {"url": 'url', "name": 'name', res: 'data.data'};
                    selectcolumn.action = website.baseUrl + "/api/sys/file/upload";
                    selectcolumn.propsHttp = {
                      // 上传完成返回的json的root
                      "res": "data.data",
                      // 上传完成返回的图片路径
                      "url": "url",
                      // 上传文件名，默认file
                      "fileName": "file",
                    };
                    selectcolumn.search = false;
                    selectcolumn.span = 24
                    break;
                }

                let formColumn = mapCols[fied.prop];
                if (formColumn) {
                  if (formColumn.dicData && !selectcolumn.dicData) {
                    selectcolumn.dicData = formColumn.dicData;
                  }
                }

                if (fied.tag && fied.tag.indexOf("overHidden") >= 0) {
                  selectcolumn.overHidden = true;
                }

                selectcolumns.push(selectcolumn);

                if (selectcolumn.dicData) {
                  this.tableDicMap[fied.prop] = {};
                  for (let ind = 0; ind < selectcolumn.dicData.length; ind++) {
                    this.tableDicMap[fied.prop][selectcolumn.dicData[ind].value] = selectcolumn.dicData[ind].label;
                  }
                }

                this.addRangSearch(selectcolumns, fied, selectcolumn);
                if (selectcolumn.type == "upload") {
                  var othercolumn = {
                    "type": "upload",
                    "label": fied.label,
                    "prop": fied.prop,
                    "overHidden": false,
                    hide: true,
                    listType: 'picture-img',
                    propsHttp: {
                      url: 'url',
                      name: 'name',
                      res: 'data.data'
                    },
                    limit: 1,
                    loadText: '图片上传中，请稍等',
                    canvasOption: {
                      text: "",
                      ratio: 0.1,
                    },
                    accept: 'image/png, image/jpeg',
                    // cropperOption: {
                    //   autoCropWidth: 100,
                    //   autoCropHeight: 100,
                    //   fixed: true,
                    //   fixedNumber: [100, 100],
                    // },
                    tip: '只能上传jpg/png文件，且不超过500kb',
                    action: website.baseUrl + "/api/sys/file/upload",
                    "rules": [{
                      required: false,
                      message: fied.label + '不能为空',
                      trigger: 'blur'
                    }],
                    'search': false,
                    "span": 24
                  }
                  selectcolumns.push(othercolumn);
                }
              }
            }
            this.option.column = selectcolumns;
            convertVantMobile(this.option, false);
          }
          this.getPage();
        });

      },

      addRangSearch(selectcolumns, fied, selectcolumn) {
        if (fied.queryType != "range") {
          return
        }
        let selectcolumnStar = {
          "type": selectcolumn.type,
          "label": "开始" + selectcolumn.label,
          "prop": selectcolumn.prop + "Star",
          'search': true,
          "labelWidth": 120,
          "hide": true,
          "span": 12
        }
        if (selectcolumn.dicData) {
          selectcolumnStar.dicData = selectcolumn.dicData;
        }
        if (selectcolumnStar.dicCode) {
          selectcolumnStar.dicCode = selectcolumn.dicCode;
        }
        if (selectcolumnStar.format) {
          selectcolumnStar.format = selectcolumn.format;
        }
        selectcolumns.push(selectcolumnStar);

        let selectcolumnEnd = {
          "type": selectcolumn.type,
          "label": "结束" + selectcolumn.label,
          "prop": selectcolumn.prop + "End",
          'search': true,
          "labelWidth": 120,
          "hide": true,
          "span": 12
        }
        if (selectcolumnEnd.dicData) {
          selectcolumnEnd.dicData = selectcolumn.dicData;
        }
        if (selectcolumnEnd.dicCode) {
          selectcolumnEnd.dicCode = selectcolumn.dicCode;
        }
        if (selectcolumnEnd.format) {
          selectcolumnEnd.format = selectcolumn.format;
        }
        selectcolumns.push(selectcolumnEnd);
        this.rangList.push(selectcolumn.prop + "Star");
        this.rangList.push(selectcolumn.prop + "End");

      },
      getDefSelected() {
        let defKeys = [];
        let defValue = this.modelValue || this.column.value;
        if (defValue) {
          if (Array.isArray(defValue)) {
            defKeys = defValue;
          } else {
            defKeys = (defValue + "").split(",");
          }
        } else {
          defKeys = [];
        }

        if (defKeys.length > 0) {
          let $that = this;

         // alert(JSON.stringify(defKeys))
          return request({
            url: website.baseUrl + '/api/' + this.pageConfig.url + '/getByKey',
            method: 'post',
            data: {},
            params: {"app": this.column.appCode, "field": this.column.filedKey, "values":defKeys.join(",")}
          }).then(response => {
            $that.selectedData = response.data.data.data || [];
          })
              .catch(() => {
                this.loading = false;
              });
        }
      },

      getPage() {
        this.loading = true;
        if (window.isMobile) {
          this.option.grid = false;
        }
        let paramsData = this.buildParam();
        return request({
          url: website.baseUrl + '/api/' + this.pageConfig.url + '/page',
          method: 'post',
          data: paramsData,
          params: {"app": this.column.appCode}
        }).then(response => {

          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.loading = false;
          if (window.isMobile) {
            this.option.grid = window.isMobile;
          }
          this.drawEcharts(this.tableData);
        })
            .catch(() => {
              this.loading = false;
            });
      },

      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
        this.page.currentPage = 1
        this.getPage(this.page);
      },
      currentChange(current) {
        this.page.currentPage = current;
        this.getPage(this.page);
      },
      refreshChange() {
        this.getPage(this.page);

      },
      searchChange(form, done) {
        this.page.currentPage = 1;
        this.getPage(this.page, form);

        done();
      },
      sortChange(column, prop, order) {

        this.sortData.sort = column.prop;
        this.sortData.order = column.order;
        this.getPage(this.page);
        // this.$message.success( this.sortData.prop+ this.sortData.order);
      },
      beforeOpen(show, type) {
        if (type == "edit") {
        }
        show();
      },

      buildParam() {
        var entity = Object.assign(
            {},
            {},
            this.form
        );
        var obj = {
          pageNum: this.page.currentPage,
          pageSize: this.page.pageSize,
        };
        obj.entity = removeEmptyFields(entity);

        if (this.sortData.sort) {
          obj.sort = this.sortData.sort
          obj.order = (this.sortData.order || "dascending") == "dascending" ? "desc" : "asc";
        }
        return obj;
      },


      selectionClick(row) {
        if (!window.isMobile) {
          return
        }
        let selection = [];
        selection.push(row);
        this.selectionChange(selection, row);
        this.handleSubmit()
      },

      selectionChange(selection, row) {

        if (!this.multiple) {
          // 如果选中列表的值大于1个
          if (selection.length > 1) {
            // 将列表中的第一个元素取出
            const preVal = selection.shift();
            // 将该选项设置为未选中
            this.$refs.crud.toggleRowSelection(preVal, false);
          }
        }

        this.selectedData = selection;

        // if (window.isMobile) {
        //
        // }
      },




      handleSubmit() {
        this.setSelectedData();
        //this.$emit('userSelected', this.selectedData);
        this.isShow = false;
      },

      handleCloseUser(tag) {
        let tags = _.filter(this.selectedData, (user) => {
          return user.id !== tag.id
        })
        this.selectedData = tags
        this.setSelectedData();
      },
      handleClearTag() {
        this.selectedData = []
        this.setSelectedData();
      },

      setSelectedData() {
        let vs = this.selectedData;
        if (!vs || vs.length == 0) {
          if (this.formData) {
            this.formData[this.column.prop] = "";
          }
          return
        }
        let values = [];
        let keyProp = this.column.filedKey||"id";
        for (let idn = 0; idn < vs.length; idn++) {
          let v = vs[idn][keyProp];
          if (v === 0) {
            continue
          }
          values.push(v);
        }

        this.selectedKey = values.join();

        if (this.formData) {
          this.formData[this.column.prop] = this.selectedKey;
        }
        this.$emit('update:modelValue', this.selectedKey);
      },
    }
  };
</script>
<style lang="scss">

.el-tag-line {
  display: block;
  margin-top: 5px;
  margin-bottom: 5px;
  font-size: 14px !important;
  padding: 2px 9px;
}

.selected-user{
  width: 160px;
  height: 500px;
}
.userSelectDialog{
  width: 80vw;height: 720px;border: 0px
}


.userSelectDiv2{
  width: 67vw;
}

.selected-user{
  width: 12vw;
}

@media only screen and (max-width: 768px) {
  .selected-user{
    width: 0px!important;
    height:  0px!important;
    display: none;

  }
  .userSelectDialog{
    width: 100vw;height: 100vh;border: 0px
  }

  .userSelectDiv1{
    width: 30vw!important;
  }

  .userSelectDiv2{
    width: 68vw!important;
  }


}
</style>
